package com.spring.tools;

import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;

import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.web.dao.JedisCache;
import com.spring.sperapc.web.model.TracelogboWithBLOBs;

public class MyTools {
	/**
	 * page_index转换rows
	 * @param page_size
	 * @param page_index
	 * @param skip
	 * @param rows
	 * @return
	 */
	public static HashMap<String,Object> pageIndexToSkip(String page_size,String page_index,String skip,String rows){
		
		int pagesize=20;
		int pageindex=1;
		int skipint=0;
		int rowsint=20;
		
		if(page_size!=null&&page_index!=null){
			
			 pagesize=Integer.parseInt(page_size);
			 pageindex=Integer.parseInt(page_index);
			
			skipint=pagesize*(pageindex-1);
			rowsint=pagesize;
			
		}else if(skip!=null&&rows!=null){
			
			 skipint=Integer.parseInt(skip);
			 rowsint=Integer.parseInt(rows);
			
		}
		
		
		HashMap<String,Object> hm=new HashMap<String,Object>();
		hm.put("skip", skipint);
		hm.put("rows", rowsint);
		
		return hm;
	}
	
	
public static HashMap<String,Object> pageIndexToSkipSearchAll(String page_size,String page_index,String skip,String rows){
		HashMap<String,Object> hm=new HashMap<String,Object>();
	
		int pagesize=20;
		int pageindex=1;
		int skipint=0;
		int rowsint=20;
		
		String searchAll=null;
		
		if(page_size!=null&&page_index!=null){
			
			 pagesize=Integer.parseInt(page_size);
			 pageindex=Integer.parseInt(page_index);
			
			skipint=pagesize*(pageindex-1);
			rowsint=pagesize;
			
		}else if(skip!=null&&rows!=null){
			
			 skipint=Integer.parseInt(skip);
			 rowsint=Integer.parseInt(rows);
			
		}else{
			searchAll="1";
			hm.put("searchAll", searchAll);
			return hm;
		}
		
		hm.put("skip", skipint);
		hm.put("rows", rowsint);
		
		return hm;
	}
	
	
	
	public static HashMap<String,Object> checkIsNotNull(String... parameter){
		HashMap<String,Object> hm = null;
		for(int i=0;i<parameter.length;i++){
			if(!ApplicationUtils.isNotNull(parameter[i])){

				hm=new HashMap<String,Object>();
				hm.put(ApplicationUtils.STATUS, "0");
				hm.put(ApplicationUtils.MSG, "请输入必要的参数");
				return hm;
			}
			
			
		}
			return hm;
	
	}
	
public static String timestampToString(String timestamp) throws Exception {
		
		Timestamp ts = new Timestamp(Integer.parseInt(timestamp)*1000);
		
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = null;

		time = sdf.format(ts);

		return time;
	}

public static List parseJsonToList(String jsonstr,Class objectClass){
	

	JSONArray json = JSONArray.fromObject(objectClass);

	List list= JSONArray.toList(json, objectClass);
	
	return list;
}


public static TracelogboWithBLOBs getLog(JedisCache jedisCache,String token,HttpServletRequest request){
	TracelogboWithBLOBs tl = getLogByRequest(request);
	
	Map<String, String> user=jedisCache.hgetAll(token);
	String userID=user.get("user_id");
	String userName=user.get("user_name");
	String deviceCategory=user.get("deviceCategory");
	if(deviceCategory!=null){
		tl.setDevicecategory(Integer.parseInt(deviceCategory));
	}
	tl.setInitialoperatorid(userID);
	tl.setInitialoperatorname(userName);
	return tl;
}

public static TracelogboWithBLOBs getLogByRequest(HttpServletRequest request){
	
	String url = request.getRequestURL()+"";	
	String ipaddress = getIpAddr(request);
	
	TracelogboWithBLOBs tl=new TracelogboWithBLOBs();
	tl.setIpaddress(ipaddress);
	tl.setUrl(url);
	return tl;
}



public static String getIpAddr(HttpServletRequest request) {
	 String ip = request.getHeader("x-forwarded-for");
	 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	  ip = request.getHeader("Proxy-Client-IP");
	 }
	 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	  ip = request.getHeader("WL-Proxy-Client-IP");
	 }
	 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	  ip = request.getRemoteAddr();
	 }
	 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	  ip = request.getHeader("http_client_ip");
	 }
	 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	  ip = request.getHeader("HTTP_X_FORWARDED_FOR");
	 }
	 // 如果是多级代理，那么取第一个ip为客户ip
	 if (ip != null && ip.indexOf(",") != -1) {
	  ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
	 }
	 return ip;
}

	@SuppressWarnings("rawtypes")
	public static String getChangeByMap(Map<String, Object> m, String type) {
		type = type==null?"修改":type;

		String change = type + ":";
		Set set = m.entrySet();
		Iterator iterator = set.iterator();
		while (iterator.hasNext()) {
			Map.Entry mapentry = (Map.Entry) iterator.next();
			if (mapentry.getValue() != null && !mapentry.getValue().equals("")) {
				change = change + mapentry.getKey() + "[" + mapentry.getValue()
						+ "],";
			}
		}
		return change;
	}

	public static String getChangeByMap(HashMap<String, Object> hm, String type) {
		Map<String, Object> m = hm;
		return getChangeByMap(m, type);
	}
	
	
	public static String getChangeByObject(Object obj, String type) throws Exception {
		type = type==null?"修改":type;

		String change = type + ":";
		
		Field[] fields = obj.getClass().getDeclaredFields();
		for (Field field : fields) {
			String key = field.getName();
			boolean access = field.isAccessible();
			if (!access)
				field.setAccessible(true);
			Object value = field.get(obj);
			if (!access)
				field.setAccessible(false);
			change = change + key + "[" + value+ "],";
		}
		return change;
	}
}
